Component({
  data: {
    selected: 0,
    color: "#999",
    selectedColor: "#1a56b8"
  },
  
  observers: {
    selected: function(index) {
      console.log('选中状态已更新为:', index);
    }
  },
  
  lifetimes: {
    attached: function() {
      // 获取全局App实例
      const app = getApp();
      
      // 从全局变量读取选中索引
      if (app.globalData) {
        this.setData({
          selected: app.globalData.tabBarIndex
        });
      }
      
      console.log('TabBar初始化, 当前选中:', this.data.selected);
    }
  },
  
  pageLifetimes: {
    show: function() {
      // 获取全局App实例
      const app = getApp();
      
      // 从全局变量更新选中索引
      if (app.globalData && this.data.selected !== app.globalData.tabBarIndex) {
        this.setData({
          selected: app.globalData.tabBarIndex
        });
      }
      
      console.log('TabBar显示, 当前选中:', this.data.selected);
    }
  },
  
  methods: {
    // 获取当前页面对应的索引
    getPageIndex: function() {
      const pages = getCurrentPages();
      if (pages.length === 0) return 0;
      
      const currentRoute = pages[pages.length - 1].route || '';
      console.log('当前页面路径:', currentRoute);
      
      if (currentRoute.includes('pages/home/')) {
        return 0;
      } else if (currentRoute.includes('pages/search/')) {
        return 1;
      } else if (currentRoute.includes('pages/message/')) {
        return 2;
      } else if (currentRoute.includes('pages/profile/')) {
        return 3;
      }
      
      return 0;
    },
    
    // 切换标签页
    switchTab: function(e) {
      const index = parseInt(e.currentTarget.dataset.index);
      console.log('用户点击切换到:', index);
      
      // 获取全局App实例
      const app = getApp();
      
      // 更新全局变量
      if (app.globalData) {
        app.globalData.tabBarIndex = index;
      }
      
      // 更新UI
      this.setData({ selected: index });
      
      // 页面跳转
      const urls = [
        "/pages/home/home",
        "/pages/search/search",
        "/pages/message/message",
        "/pages/profile/profile"
      ];
      
      wx.switchTab({
        url: urls[index]
      });
    },
    
    // 中间按钮点击
    onCenterButtonClick: function() {
      wx.showActionSheet({
        itemList: ['发布动态', '创建活动', '上传作品'],
        success: (res) => {
          const index = res.tapIndex;
          let url = '';
          
          switch(index) {
            case 0: url = '/pages/publish/dynamic'; break;
            case 1: url = '/pages/publish/event'; break;
            case 2: url = '/pages/publish/work'; break;
          }
          
          if (url) {
            wx.navigateTo({ url });
          }
        }
      });
    }
  }
});